<template>
	<view>
		<nav-bar title="立即充电"></nav-bar>
		<image :style="{'top':navHeight+'px'}" class="top-bg" src="https://oss.jxhecong.com/v2/image/bike_top_bg@2x.png"></image>
		<scroll-view :style="{'margin-top':(navHeight+10)+'px'}">
			<view class="card">
				<bike-device-cell  :showSiteName="true" :data="chargingDetail"></bike-device-cell>
			</view>
			<view class="card box" style="margin-top:24rpx;">
				<select-socket-or-mode 
				title="请选择充电插座" 
				@selectChange="selectSocketChange" 
				:rowCount="4"
				:current="currentSocketIndex"
				:dataList="chargingDetail.socketList"></select-socket-or-mode>
			</view>
			<view class="card box" style="margin-top:24rpx;">
				<select-socket-or-mode 
				title="请选择计费方式" 
				subNextTitle="收费详情"
				@nextChange="showPop"
				@selectChange="selectChange" 
				:rowCount="3"
				:current="currentIndex"
				:dataList="chargingDetail.billingPlanList"></select-socket-or-mode>
			</view>
			<view class="card box" style="margin-top:24rpx;" v-if="chargingDetail.memberRight.billingMethod != 1">
				<view class="coupon-box">
					<view class="coupon-title">{{chargingDetail.memberRight.billingMethodDesc}}</view>
					<view>
						<view class="coupon-title" style="font-size:28rpx;text-align: right;">{{chargingDetail.memberRight.billingMethodDesc}}</view>
						<view style="color: #909399;font-size:24rpx;text-align: right;">还可用<text style="color:#00C3A6;">{{chargingDetail.memberRight.remain}}</text>次，每次<text style="color: #00C3A6;">{{chargingDetail.memberRight.price}}</text>元</view>
					</view>
				</view>
			</view>
			<view class="card box flex" style="margin-top:24rpx;">
				<view>
					<text>钱包余额</text>
					<text class="remain">（{{userInfo.totalMoney}}）</text>
				</view>
				<text style="color: #6ABF6C;height: 80rpx;line-height: 80rpx;" @click.stop="toCharge">去充值</text>
			</view>
		</scroll-view>
		<view style="height:200rpx;"></view>
		<view class="footer">
			<view style="margin-left: 30rpx;" v-if="chargingDetail.memberRight.billingMethod==3">
				<view class="price">
					<text style="font-size: 24rpx;color: #606266;margin-right: 10rpx;">价格</text>
					<text>¥</text>
					<text style="display: inline-block;margin-left:10rpx;">{{chargingDetail.memberRight.price}}</text>
				</view>
				<view class="new-user">{{chargingDetail.memberRight.remark}}</view>
			</view>
			<view :class="{'scan': chargingDetail.memberRight.billingMethod==3?true:false, 'scan-bar':chargingDetail.memberRight.billingMethod==3?false:true}" @click.stop="charge_Click">
				<text>开始充电</text>
			</view>
		</view>
		<new-user-pop-view ref="newUserPopView" :tips="activityInfo.tips" @onClick="receiveActivity"></new-user-pop-view>
		<power-pop-view ref="powerPopView"></power-pop-view>
		<recharge-pop-view ref="rechargePopView"></recharge-pop-view>
		<charging-progress-pop-view :show="showCharging" :percent="percent"></charging-progress-pop-view>
	</view>
</template>

<script>
	var globalData = getApp({
		allowDefault: true
	}).globalData
	import navBar from '../components/navBar.vue'
	import bikeDeviceCell from '../components/bikeDeviceCell.vue'
	import selectSocketOrMode from '../components/selectSocketOrMode.vue'
	import powerPopView from '../site/powerPopView.vue'
	import chargingProgressPopView from '../components/chargingProgressPopView.vue'
	import rechargePopView from './rechargePopView.vue'
	import newUserPopView from './newUserPopView.vue'
	import * as chargeApi from '../../api/charge/index.js'
	import * as homeApi from '@/api/home/index.js'
	import * as userApi from '../../api/user/index.js'
	var timer = null
	var resultTimer = null
	export default{
		components:{
			bikeDeviceCell,
			navBar,
			selectSocketOrMode,
			powerPopView,
			rechargePopView,
			newUserPopView,
			chargingProgressPopView},
		data(){
			return{
				id:'',
				activityInfo:{},
				userInfo:{},
				navHeight:0,
				currentSocketIndex:0,
				currentIndex:0,
				showCharging:false,
				percent:0,
				chargingDetail:{
					chargingId:'',
					name:'',
					shellId:'',
					level:'',
					status:'',
					chargingGroupName:'',
					socketList:[],
					billingPlanList:[],
					chargingGroupId:'',
					memberRight:{
						billingMethod:1,
						billingMethodDesc:'',
						remark:'',
						tips:''
					}
				}
			}
		},
		onShow() {
			let userInfo=uni.getStorageSync('userInfo')
			if(userInfo) {
				this.getUserInfo()
			}
		},
		onUnload() {
			globalData.qrCode=""
			this.clearTimer()
		},
		onHide() {
			this.clearTimer()
		},
		onLoad(options) {
			// #ifdef MP
			let url = ""
			let shellId=""
			let data=""
			// #ifdef MP-WEIXIN
			url = decodeURIComponent(options.q)
			data = url.split('shell=')[1]
			shellId = options.shellId
			// #endif
			// #ifdef MP-ALIPAY
			url = decodeURIComponent(globalData.qrCode)
			data = url.split('shell=')[1]
			shellId = options.shellId
			// #endif
			if (data || shellId) {
				data = data ? data : shellId
				let userInfo=uni.getStorageSync('userInfo')
				if(!userInfo) {
					uni.reLaunch({
						url:'/pages/login/login?type=0&shell=' + data
					})
					return
				}
				this.getChargeIdByQRCode(data,(id)=>{
					this.id=id;
					this.getChargeDetail();
					this.getUserInfo()
				})
			} else {
				this.id=options.id;
				this.getChargeDetail();
				this.getUserInfo()
			}
			// #endif
			// #ifdef APP-PLUS || APP-PLUS-NVUE
			this.id=options.id;
			this.getChargeDetail();
			// #endif
			this.navHeight = globalData.titleHeight;
		},
		methods:{
			selectSocketChange(e){
				this.currentSocketIndex=e.index
				console.log('## 插座选择值 ## ' + this.currentSocketIndex)
			},
			selectChange(e){
				this.currentIndex=e.index
				console.log('## 计费选择值 ## ' + this.currentIndex)
			},
			showPop(){
				this.$refs['powerPopView'].open(this.chargingDetail.chargingGroupId)
			},
			getChargeDetail() {
				chargeApi.getChargingDetail(this.id).then((res)=>{
					console.log(res.data)
					res.data.billingPlanList.map((item)=>{
						this.$set(item,'name', item.value)
					})
					res.data.socketList.map((item)=>{
						this.$set(item,'name', item.value)
					})
					this.chargingDetail = res.data
					this.getActivityInfo()
					
				}).catch((errMsg)=>{
					uni.showToast({
						title:errMsg,
						icon:'none'
					})
				})
			},
			
			getChargeIdByQRCode(qrcode,callback){
				homeApi.getChargeScan(qrcode).then((res) => {
					uni.hideLoading()
					typeof callback == 'function'&&callback(res.data.chargingId)
				}).catch((errMsg) => {
					uni.showToast({
						title:errMsg,
						icon:'none'
					})
				})
			},
			
			processClock(){
				let seconds = 30
				timer = setInterval(()=>{
					seconds = seconds - 0.1
					if (this.percent < 90) {
						this.percent = this.percent + 100 / 300
					}
					if (seconds <= 0) {
						clearInterval(timer)
						clearInterval(resultTimer)
						this.showCharging = false
						this.percent = 0
						uni.showToast({
							title: '充电失败，请再试一次',
							icon: 'none'
						})
					}
				},100)
			},
			
			pollingCharging(orderNumber,callback){
				resultTimer=setInterval(()=>{
					this.getChargeResult(orderNumber,callback)
				},1000)
			},
			
			getChargeResult(orderNumber,callback){
				chargeApi.confirmCharge(orderNumber).then((res)=>{
					if(res.code == 0){
						console.log('## 确认回复请求 ## ' + res.data)
						this.clearTimer();
						this.getChargeDetail()
						typeof callback==='function'&&callback('success')
					}
				}).catch((error)=>{
					this.showCharging = false
					this.percent = 0
					this.clearTimer()
					uni.showToast({
						title:errorMsg,
						icon:'none'
					})
				})
			},
			clearTimer(){
				clearInterval(timer)
				clearInterval(resultTimer)
			},
			
			endProgerss(orderNumber){
				let duration = 0.2
				let lastPercent = 100 - this.percent
				let endTimer = setInterval(()=>{
					duration = duration - 0.1
					this.percent = this.percent + lastPercent / 2.0
					if (duration < 0) {
						this.showCharging = false
						this.percent = 0
						clearInterval(endTimer)
						uni.redirectTo({
							url: '/pages/order/chargingDetail?deviceType=0&orderNumber='+orderNumber
						})
					}
				},100)
			},
			
			charge_Click(){
				this.showCharging = true;
				this.percent = 0;
				this.processClock()
				chargeApi.startCharge(this.chargingDetail.socketList[this.currentSocketIndex].id,this.chargingDetail.billingPlanList[this.currentIndex].id).then((res)=>{
					if(res.code == 1041) {
						this.showCharging = false
						this.percent = 0
						this.clearTimer();
						uni.showModal({
							title:'余额不足，请充值',
							success: (res) => {
								if(res.confirm) {
									this.$refs['rechargePopView'].open(this.chargingDetail.chargingGroupId)
								}
							}
						})
						
					} else {
						let orderNumber=res.data.orderNumber;
						this.pollingCharging(orderNumber,()=>{
							this.endProgerss(orderNumber)
						})
					}
				}).catch((errorMsg)=>{
					this.showCharging = false
					this.percent = 0
					this.clearTimer();
					uni.showToast({
						title:errorMsg,
						icon:'none'
					})
				})
			},
			getUserInfo(){
				let userInfo=uni.getStorageSync('userInfo')
				if (userInfo) {
					userApi.getUserInfo().then((res) => {
						if (res.code == 0) {		
							this.userInfo = res.data
						}		
					}).catch((errMsg) => {
					
					})
				}
			},
			toCharge(){
				this.$refs['rechargePopView'].open(this.chargingDetail.chargingGroupId)
			},
			getActivityInfo(){
				chargeApi.getActivityInfo(this.chargingDetail.chargingGroupId).then((res)=>{
					if(res.code==0){
						this.activityInfo=res.data
						this.$refs.newUserPopView.open()
					}
				})
			},
			receiveActivity(){
				uni.showLoading({
					title:'领取中'
				})
				chargeApi.receiveActivity(this.chargingDetail.chargingGroupId).then((res)=>{
					uni.hideLoading()
					if(res.code==0){
						this.show=false
						uni.showToast({
							title:'领取成功',
							icon:'none'
						})
						this.getChargeDetail()
					}
				}).catch((errMsg)=>{
					this.show=false
					uni.hideLoading()
					uni.showToast({
						title:errMsg,
						icon:'none'
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.top-bg{
		position: fixed;
		left:0rpx;
		right:0rpx;
		height:112rpx;
		width:100%;
		z-index: 0;
	}
	.card{
		position: relative;
		background: #FFFFFF;
		box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.06);
		border-radius: 9px;
		margin-left:30rpx;
		margin-right:30rpx;
		overflow: hidden;
	}
	.box{
		padding:30rpx;
	}
	.footer{
		position: fixed;
		left:0rpx;
		right:0rpx;
		bottom:0rpx;
		height:116rpx;
		background-color:#FFFFFF;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: env(safe-area-inset-bottom);
	}
	.scan{
		background: #6ABF6C;
		box-shadow: 0px 1px 2px 0px rgba(8,139,120,0.3);
		height:90rpx;
		width: 320rpx;
		border-radius:45rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-right:30rpx;
		image{
			width:42rpx;
			height:42rpx;
		}
		text{
			color:#FFFFFF;
			font-size:36rpx;
			margin-left:24rpx;
		}
	}
	.scan-bar{
		background: #6ABF6C;
		box-shadow: 0px 1px 2px 0px rgba(8,139,120,0.3);
		height:90rpx;
		border-radius:45rpx;
		display: flex;
		width: 100%;
		justify-content: center;
		align-items: center;
		margin-right:30rpx;
		margin-left: 30rpx;
		image{
			width:42rpx;
			height:42rpx;
		}
		text{
			color:#FFFFFF;
			font-size:36rpx;
			margin-left:24rpx;
		}
	}
	.coupon-box{
		display: flex;
		justify-content: space-between;
		align-items: center;
		.coupon-title{
			color:#303133;
			font-size:32rpx;
		}
	}
	.price{
		width:300rpx;
		color:#6ABF6C;
		font-size:42rpx;
		font-weight: bold;
	}
	.remain{
		color: #D00000;
		font-size: 32rpx;
	}
	.flex{
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.new-user{
		color: #FA3534;
		font-size: 24rpx;
	}
</style>
